import Taro, { useDidShow } from "@tarojs/taro";
import Router from "./router";
import days from "dayjs";

export const goBack = function (fn) {
  Taro.navigateBack({
    delta: 1, // 返回上一级页面
    success: () => {
      fn && fn();
    },
  });
};
export const CopyToClipboard = (e, success) =>
  Taro.setClipboardData({
    data: e,
    success: (e) => {
      Taro.showToast({
        title: success || "复制成功",
        icon: "none",
      });
    },
    fail: (e) => {
      Taro.showToast({
        title: "复制失败",
        icon: "none",
      });
    },
  });
export const toast = (value, fn) => {
  return Taro.showToast({
    title: value,
    icon: "none",
    duration: 3000,
    mask: true,
    success: () => {
      fn && fn();
    },
  });
};
//小提示弹窗
export const objStatus = (obj) => {
  if (Object.keys(obj).length > 0) {
    return true;
  }
  return false;
};
//判断对象里面是否有值
export const addPhotosAlbum = (path) => {
  Taro.showLoading({
    title: "正在保存",
    mask: true,
  });
  Taro.saveImageToPhotosAlbum({
    filePath: path, //canvasToTempFilePath返回的tempFilePath
    success: (res) => {
      Taro.hideLoading();
      toast("成功保存相册");
    },
    fail: (err) => {
      Taro.hideLoading();
      toast("保存失败");
    },
    complete: () => { },
  });
};
//保存照片进相册 path 照片路径
export const loginData = () => {
  const { token = "" } = Taro.getStorageSync("userInfo") || {};
  if (token) {
    return Taro.getStorageSync("userInfo");
  } else {
    return false;
  }
};
//用户是否登录
export const backgroundObj = function (url) {
  if (url) {
    return {
      background: `url(${url}) no-repeat center/cover`,
    };
  }
  return {};
};
//设置背景图片
export const getLat = () => {
  return Taro.getStorageSync("lat");
};
//用户精度
export const getLnt = () => {
  return Taro.getStorageSync("lnt");
};
//用户维度
export const filterStrList = (str) => {
  if (!str || str.length == 0) {
    return [];
  }
  return str.split(",");
};
export const fetchStorage = (key) => {
  return Taro.getStorageSync(key);
};
//读取微信缓存
export const fakeStorage = (key, val) => {
  return Taro.setStorageSync(key, val);
};
//设置微信缓存
export const fakeRemoveStorage = (key) => {
  return Taro.removeStorageSync(key);
};
export const getDom = (id, fn) => {
  Taro.createSelectorQuery()
    .selectAll(id)
    .boundingClientRect(function (rect) {
      fn(rect);
    })
    .exec();
};
//获取微信元素位置信息
export const format = (time = "") => {
  if (new Date().getTime() > new Date(time.replace(/-/g, "/")).getTime()) {
    return true;
  }
  return false;
};
export const mapGo = (item) => {
  Taro.openLocation({
    latitude: parseFloat(item.lat),
    longitude: parseFloat(item.lnt),
    address: item.address || "",
    name: item.merchantName || "",
  });
};

export const mapSelect = (fn) => {
  wx.chooseLocation({
    success: (val) => {
      const { address, name, latitude, longitude } = val;
      return fn({
        address: name,
        lat: latitude,
        lnt: longitude,
        location: address,
      });
    },
    fail: () => {
      toast("获取微信位置失败");
    },
  });
};
//选择地址

export const removeLogin = () =>
  Taro.removeStorage({
    key: "userInfo",
    success: (res) => { },
    fail: (res) => {
      toast("缓存清理错误");
    },
  });
//删除用户信息
export const removeStorage = (key) =>
  Taro.removeStorage({
    key: key,
    success: (res) => { },
    fail: (res) => {
      toast("缓存清理错误");
    },
  });
//清理缓存

export const setSessionItem = (data) => {
  const session = Taro.getStorageSync("userInfo");
  Taro.setStorageSync("userInfo", { ...session, ...data });
};

export const wechatAuth = (callback) => {
  Taro.login({
    success: (e) => {
      const { code } = e;
      callback && callback(code);
    },
    fail: (e) => {
      toast("获取微信登录信息失败");
    },
  });
  // Taro.checkSession({
  //   success: () => {
  //     const code = Taro.getStorageSync("code");
  //     callback && callback(code);
  //   },
  //   fail: () => {

  //   },
  // });
};

export const setString = (randomFlag, min, max) => {
  var str = "",
    range = min,
    arr = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
      "A",
      "B",
      "C",
      "D",
      "E",
      "F",
      "G",
      "H",
      "I",
      "J",
      "K",
      "L",
      "M",
      "N",
      "O",
      "P",
      "Q",
      "R",
      "S",
      "T",
      "U",
      "V",
      "W",
      "X",
      "Y",
      "Z",
    ];

  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min;
  }
  for (var i = 0; i < range; i++) {
    let pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
};

export const dataParams = (params) => {
  return Object.keys(params)
    .filter(key => params[key] != null && params[key] !== '') // 排除无效值
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`) // 编码特殊字符
    .join('&');
};

export const formatRichText = (html = "") => {
  console.log(html, 1111);
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "");
    match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "");
    match = match
      .replace(/height="[^"]+"/gi, "")
      .replace(/height='[^']+'/gi, "");
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, "max-width:100%;")
      .replace(/width:[^;]+;/gi, "max-width:100%;");
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, "");
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
  );
  return newContent;
};

export const handleLink = (type, url) => {
  function getFileExtension(fileName) {
    // 使用正则表达式匹配文件名中的后缀部分
    const regex = /(?:\.([^.]+))?$/;
    const result = regex.exec(fileName);

    // 提取匹配到的后缀，如果没有后缀则返回空字符串
    const extension = result ? result[1] : "";

    return extension;
  }
  if (getFileExtension(url) === "pdf") {
    Taro.downloadFile({
      url: url,
      success: function (res) {
        var filePath = res.tempFilePath;
        Taro.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log("打开文档成功！");
          },
          fail: () => {
            CopyToClipboard(url, "复制链接成功,请前往浏览器打开或下载");
          },
        });
      },
    });
  } else {
    Router("renderLink", { args: { url: url } });
  }
};
